package org.xwb.pecs;

import java.util.List;
import java.util.stream.IntStream;
// 非线程安全的累加操作
class UnsafeCounter {
    private int count = 0;
    public void increment() { count++; }
    public int getCount() { return count; }
}

public class Parallel {


    public static void main(String[] args) {
        UnsafeCounter unsafeCounter = new UnsafeCounter();
        // 使用并行流累加（错误示例）
        IntStream.range(0, 10000)
                .parallel()
                .forEach(i -> unsafeCounter.increment());

        System.out.println("并行流结果（不安全）: " + unsafeCounter.getCount());

        List<Integer> numbers = IntStream.range(0, 1_000_000).boxed().toList();

        // 顺序流耗时
        long seqStart = System.currentTimeMillis();
        numbers.stream().reduce(0, Integer::sum);
        long seqTime = System.currentTimeMillis() - seqStart;

        // 并行流耗时
        long parStart = System.currentTimeMillis();
        numbers.parallelStream().reduce(0, Integer::sum);
        long parTime = System.currentTimeMillis() - parStart;

        System.out.println("顺序流时间: " + seqTime + "ms");
        System.out.println("并行流时间: " + parTime + "ms");
    }


}
